package com.njlime.core.sdk.wechat;


import com.njlime.core.helper.SpringContextHolder;
import com.njlime.core.web.AppWxInterceptor;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.service.UnitService;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 响应来自微信服务器的Token Url验证请求
 *
 */
public class OpenidServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private UnitService unitService;

    public OpenidServlet() {
        super();
        this.unitService = SpringContextHolder.getBean("unitService");
    }

    public void destroy() {
        super.destroy();
    }

    /**
     * 验证微信Token
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("OpenidServlet doGet");
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        //获取微信授权
        String code = request.getParameter("code");
        Logger.getLogger(this.getClass()).debug("微信Code：" + code);
        Integer unit_id = Integer.valueOf(request.getParameter("state"));
        UnitWxConfig wxConfig = unitService.getWxConfig(unit_id);
        String openid = WeChatUtil.getOpenId(wxConfig.getApp_id(), wxConfig.getApp_secret(), code);
        request.getSession().setAttribute(AppWxInterceptor.WX_USER_OPENID, openid);
        Logger.getLogger(this.getClass()).debug("微信openid：" + openid);
        String backUrl = new String(Base64.decodeBase64(request.getParameter("backUrl").getBytes("UTF-8")), "UTF-8");
        Logger.getLogger(this.getClass()).debug("跳转地址：" + backUrl);
        response.sendRedirect(backUrl);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("OpenidServlet doPost");

    }

}
